// Copyright (c) 2008 Davy Brion (ralinx@davybrion.com)
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of Davy Brion nor the names of the
//       contributors may be used to endorse or promote products derived from this
//       software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System.Linq;
using System.Collections;
using System.Collections.Generic;

using NHibernate;
using NHibernate.Criterion;

namespace NHibernate.Servicelayer.NHibernate
{
    public class QueryBatcher : IQueryBatcher
    {
        private readonly Dictionary<string, int> criteriaResultPositions;
        private readonly List<ICriteria> criteriaList;
        private readonly List<IQuery> hqlQueryList;
        private readonly Dictionary<string, int> queryResultPositions;
        private readonly ISession session;

        private IList criteriaResults;
        private IList queryResults;

        public QueryBatcher(IActiveSessionManager activeSessionManager)
        {
            session = activeSessionManager.GetActiveSession();
            criteriaList = new List<ICriteria>();
            hqlQueryList = new List<IQuery>();
            criteriaResultPositions = new Dictionary<string, int>();
            queryResultPositions = new Dictionary<string, int>();
        }

        public void AddCriteria(string key, ICriteria criteria)
        {
            criteriaList.Add(criteria);
            criteriaResultPositions.Add(key, criteriaList.Count - 1);
        }

        public void AddCriteria(string key, DetachedCriteria detachedCriteria)
        {
            AddCriteria(key, detachedCriteria.GetExecutableCriteria(session));
        }

        public object GetResult(string key)
        {
            ExecuteQueriesIfNecessary();
            object result = GetResultFromList(key, criteriaResults, criteriaResultPositions);
            if (result != null) return result;
            result = GetResultFromList(key, queryResults, queryResultPositions);
            if (result != null) return result;

            return null;
        }

        public IEnumerable<T> GetEnumerableResult<T>(string key)
        {
            var list = GetResult<IList>(key);
            return list.Cast<T>();
        }

        public T GetSingleResult<T>(string key)
        {
            var result = GetResult<IList>(key);
            return (T)result[0];
        }

        public void AddHqlQuery(string key, IQuery query)
        {
            hqlQueryList.Add(query);
            queryResultPositions.Add(key, hqlQueryList.Count - 1);
        }

        public void AddHqlQuery(string key, string query)
        {
            AddHqlQuery(key, session.CreateQuery(query));
        }

        public void ExecuteQueriesIfNecessary()
        {
            ExecuteCriteriaIfNecessary();
            ExecuteHqlIfNecessary();
        }

        private void ExecuteCriteriaIfNecessary()
        {
            if (criteriaList.Count > 0 && criteriaResults == null)
            {
                if (criteriaList.Count == 1)
                {
                    criteriaResults = new ArrayList { criteriaList[0].List() };
                }
                else
                {
                    var multiCriteria = session.CreateMultiCriteria();
                    criteriaList.ForEach(c => multiCriteria.Add(c));
                    criteriaResults = multiCriteria.List();
                }
            }
        }

        private void ExecuteHqlIfNecessary()
        {
            if (hqlQueryList.Count > 0 && queryResults == null)
            {
                if (hqlQueryList.Count == 1)
                {
                    queryResults = new ArrayList { hqlQueryList[0].List() };
                }
                else
                {
                    var multiQuery = session.CreateMultiQuery();
                    hqlQueryList.ForEach(q => multiQuery.Add(q));
                    queryResults = multiQuery.List();
                }
            }
        }

        private T GetResult<T>(string key)
        {
            return (T)GetResult(key);
        }

        private static object GetResultFromList(string key, IList list, IDictionary<string, int> positions)
        {
            if (positions.ContainsKey(key)) return list[positions[key]];
            return null;
        }
    }
}